package com.tmc.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.tmc.bean.common.CommonResult;
import com.tmc.bean.common.ContextInfo;
import com.tmc.bean.common.Pagination;
import com.tmc.constant.FareConstant.PolicyStatus;
import com.tmc.entity.intair.CommisionPolicy;
import com.tmc.service.intair.CommisionPolicyServiceImpl;
import com.tmc.web.BaseController;

@Controller
@RequestMapping("/commisionpolicy")
public class CommisionPolicyController extends BaseController {

	@Autowired
	private CommisionPolicyServiceImpl policyService;

	@Value("${upload_path}")
	private String upload_path;

	@Value("${template_path}")
	private String template_path;

	/**
	 * 返点政策列表
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ModelAndView policyList(CommisionPolicy cond, Integer pageIndex, Integer pageSize, HttpServletRequest request) {
		ContextInfo context = this.getContextInfo(request);
		if (pageIndex == null || pageIndex < 1)
			pageIndex = 1;
		if (pageSize == null || pageIndex < 1 || pageIndex > 1000)
			pageSize = 10;
		Map<String, Object> map = new HashMap<String, Object>();
		Pagination<CommisionPolicy> page = policyService.findPolicysByCon(context, cond, pageIndex, pageSize);
		map.put("page", page);
		map.put("cond", cond);
		map.put("context", context);
		return new ModelAndView("views/policy/policy-list", map);
	}

	/**
	 * 保存政策页面跳转
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/editPage")
	public ModelAndView editPage(Long policyId, HttpServletRequest request) {
		ContextInfo context = this.getContextInfo(request);
		Map<String, Object> map = new HashMap<String, Object>();
		CommisionPolicy policy = null;
		if (policyId != null)
			policy = policyService.getById4Show(context, policyId);
		else
			policy = new CommisionPolicy();
		map.put("policy", policy);
		map.put("context", context);
		return new ModelAndView("views/policy/policy-edit", map);
	}

	/**
	 * 保存政策
	 * 
	 * @param policy
	 * @return
	 */
	@RequestMapping(value = "/save")
	@ResponseBody
	public String save(CommisionPolicy policy, BindingResult result, HttpServletRequest request) {
		ContextInfo context = this.getContextInfo(request);
		if (result.hasErrors()) {
			return JSON.toJSONString(CommonResult.makeFail(result.getFieldError().getDefaultMessage()));
		}
		CommonResult cr = policyService.savePolicy(context, policy);
		return cr.toJson();
	}

	/**
	 * 删除政策
	 * 
	 * @param policy
	 * @return
	 */
	@RequestMapping(value = "/delete{policyId}")
	@ResponseBody
	public String policyDelete(Long policyId, HttpServletRequest request) {
		ContextInfo context = this.getContextInfo(request);
		CommonResult cr = policyService.deletePolicy(context, policyId);
		return cr.toJson();
	}

	/**
	 * 删除政策
	 * 
	 * @param policy
	 * @return
	 */
	@RequestMapping(value = "/deleteAll{policyIds}")
	@ResponseBody
	public String policysDelete(String policyIds, HttpServletRequest request) {
		ContextInfo context = this.getContextInfo(request);
		CommonResult cr = policyService.deletePolicys(context, policyIds);
		return cr.toJson();
	}

	/**
	 * 上架政策
	 * 
	 * @param policy
	 * @return
	 */
	@RequestMapping(value = "/puton{policyId}")
	@ResponseBody
	public String policyPutOn(Long policyId, HttpServletRequest request) {
		ContextInfo context = this.getContextInfo(request);
		CommonResult cr = policyService.changePolicyStatus(context, policyId, PolicyStatus.UP.getStatus());
		if (cr.isSuccess()) {
			cr.setMessage("已发布！");
		}
		return cr.toJson();
	}

	/**
	 * 上架政策
	 * 
	 * @param policy
	 * @return
	 */
	@RequestMapping(value = "/putons{policyIds}")
	@ResponseBody
	public String policysPutOn(String policyIds, HttpServletRequest request) {
		ContextInfo context = this.getContextInfo(request);
		CommonResult cr = policyService.changePolicysStatus(context, policyIds, PolicyStatus.UP.getStatus());
		if (cr.isSuccess()) {
			cr.setMessage("已发布！");
		}
		return cr.toJson();
	}

	/**
	 * 下架政策
	 * 
	 * @param policy
	 * @return
	 */
	@RequestMapping(value = "/pulloff{policyId}")
	@ResponseBody
	public String policyPullOff(Long policyId, HttpServletRequest request) {
		ContextInfo context = this.getContextInfo(request);
		CommonResult cr = policyService.changePolicyStatus(context, policyId, PolicyStatus.DOWN.getStatus());
		if (cr.isSuccess()) {
			cr.setMessage("已下架！");
		}
		return cr.toJson();
	}

	/**
	 * 下架政策
	 * 
	 * @param policy
	 * @return
	 */
	@RequestMapping(value = "/pulloffs{policyIds}")
	@ResponseBody
	public String policysPullOff(String policyIds, HttpServletRequest request) {
		ContextInfo context = this.getContextInfo(request);
		CommonResult cr = policyService.changePolicysStatus(context, policyIds,
				PolicyStatus.DOWN.getStatus());
		if (cr.isSuccess()) {
			cr.setMessage("已下架！");
		}
		return cr.toJson();
	}
	/**
	 * 复制政策
	 * 
	 * @param policyId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/copy")
	public ModelAndView policyCopy(Long policyId, HttpServletRequest request) {
		ContextInfo context = this.getContextInfo(request);
		Map<String, Object> map = new HashMap<String, Object>();
		CommisionPolicy policy = null;
		if(policyId != null){
			policy = policyService.copyPolicy(context,policyId);
		}else{
			policy = new CommisionPolicy();
		}
		map.put("policy", policy);
		return new ModelAndView("views/policy/policy-edit", map);
	}
	
	/**
	 * 匹配本地政策
	 * 
	 * @param orderId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/searchNativePolicy",method=RequestMethod.POST)
	@ResponseBody
	public  String searchNativePolicy(Long orderId, HttpServletRequest request) {
		ContextInfo context = this.getContextInfo(request);
		CommonResult cr = policyService.matchNativePolicy(context, orderId);
		
		if(!cr.isSuccess()){
			cr.setMessage("未匹配到政策!");
		}
		return cr.toJson();
	}
	
	public class Object1 {
		private String orderId;

		public String getOrderId() {
			return orderId;
		}

		public void setOrderId(String orderId) {
			this.orderId = orderId;
		}
	}
	
	@RequestMapping(value = "/uploadpage")
	public ModelAndView policyUploadPage(String policyIds, HttpServletRequest request) {
		ContextInfo context = this.getContextInfo(request);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("policyIds", policyIds);
		map.put("context", context);
		return new ModelAndView("views/policy/policy-upload", map);
	}

	@RequestMapping(value = "/importpage")
	public ModelAndView policyImportPage(HttpServletRequest request) {
		ContextInfo context = this.getContextInfo(request);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("template_path", template_path + "公布运价佣金政策.xlsx");
		map.put("context", context);
		return new ModelAndView("views/policy/policy-import", map);
	}

	/*@RequestMapping(value = "/fileImport")
	@ResponseBody
	public String fileImport(HttpServletRequest request, HttpServletResponse response) {
		try {
			// 转型为MultipartHttpRequest：
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			// 获得文件：
			MultipartFile file = multipartRequest.getFile("file");
			System.out.println("导入返点政策文件：" + file.getOriginalFilename());
			String filename = new Date().getTime() + "_" + file.getOriginalFilename();
			String path = upload_path + "commision_policy/";
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			File newFile = new File(path + filename);
			// 通过CommonsMultipartFile的方法直接写文件（注意这个时候）
			file.transferTo(newFile);
			policyService.importPolicyFile(new ContextInfo(), newFile);
			return CommonResult.makeSuccess().toJson();
		} catch (Exception e) {
			return CommonResult.makeFail(e.getMessage()).toJson();
		}
	}

	@Value("${export_path}")
	private String export_path;
	
	@RequestMapping(value = "/exportExcel{policyIds}", produces = {"application/vnd.ms-excel;charset=UTF-8"})
	public void policyExportExcel(String policyIds, HttpServletResponse response) {
		CommonResult cr = policyService.exportExcel(new ContextInfo(), policyIds, export_path);
		if (cr.isSuccess()) {
			try {
				String path = (String) cr.getObj();
				if (ObjectUtil.noText(path)){
					return;
				}
				String fileName = path.substring(path.lastIndexOf("\\") + 1);
				response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
				InputStream in = new FileInputStream(path);
				int len = 0;
				byte[] buffer = new byte[1024];
				OutputStream out = response.getOutputStream();
				while ((len = in.read(buffer)) > 0) {
					out.write(buffer, 0, len);
				}
				in.close();
			} catch (Exception e) {
				logger.error("导出excel出错！", e);
			}
		}
	}*/
	
}
